package com.pond.pond.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pond.pond.domain.*;
import com.pond.common.core.utils.DateUtils;
import com.pond.pond.client.DeptClient;
import com.pond.pond.client.SysUserClient;
import com.pond.pond.domain.*;
import com.pond.pond.domain.dto.PondDTO;
import com.pond.pond.domain.dto.PondFacilityDTO;
import com.pond.pond.domain.vo.PondCommentVo;
import com.pond.pond.domain.vo.PondNameOptionsVo;
import com.pond.pond.mapper.DeptFacilityRelationMapper;
import com.pond.pond.mapper.PondCommentImageMapper;
import com.pond.pond.mapper.PondCommentMapper;
import com.pond.system.api.domain.SysDept;
import com.pond.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pond.pond.mapper.PondMapper;
import com.pond.pond.service.IPondService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 鱼塘管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-13
 */
@Slf4j
@Service
public class PondServiceImpl implements IPondService
{
    @Autowired
    private PondMapper pondMapper;
    @Autowired
    private PondCommentMapper pondCommentMapper;
    @Autowired
    private PondCommentImageMapper pondCommentImageMapper;
    @Autowired
    private DeptFacilityRelationMapper deptFacilityRelationMapper;
    @Autowired
    private SysUserClient sysUserClient;

    @Autowired
    private DeptClient deptClient;

    @Override
    public Pond selectPondById(Long id)
    {
        return pondMapper.selectPondById(id);
    }

    @Override
    public List<Pond> selectPondList(Pond pond)
    {
        List<Pond> pondList = pondMapper.selectPondList(pond);
        if (pondList.isEmpty()) {
            return pondList;
        }

        List<Long> ids = pondList.stream().map(Pond::getId).collect(Collectors.toList());
        List<PriceSegment> allPriceSegment = pondMapper.selectPriceSegmentsByPondIds(ids);
        Map<Long, List<PriceSegment>> segmentMap = allPriceSegment.stream()
                .filter(segment -> segment.getPondId() != null)
                .collect(Collectors.groupingBy(PriceSegment::getPondId));
        for (Pond p : pondList) {
            p.setPriceSegments(segmentMap.get(p.getId()));

        }

        return pondList;
    }

    @Override
    public List<PondNameOptionsVo> selectPondOptionList()
    {
        return pondMapper.selectPondOptionList();
    }

    @Override
    public int insertPond(PondDTO pondDTO) {
        pondDTO.setCreateTime(DateUtils.getNowDate());

        // ✅ DTO → Entity
        Pond pond = new Pond();
        pond.setName(pondDTO.getName());
        pond.setDeptId(pondDTO.getDeptId());
        pond.setBackgroundUrl(pondDTO.getBackgroundUrl());
        pond.setIsReturnFish(pondDTO.getIsReturnFish());
        pond.setCurrentWeight(pondDTO.getCurrentWeight());
        pond.setRemark(pondDTO.getRemark());
        pond.setCreateTime(pondDTO.getCreateTime());

        // fishTypes List → String
        if (pondDTO.getFishTypes() != null && !pondDTO.getFishTypes().isEmpty()) {
            pond.setFishTypes(String.join(",", pondDTO.getFishTypes()));
        } else {
            pond.setFishTypes(null);
        }

        int rows = pondMapper.insertPond(pond);

        // ✅ 把生成的主键 ID 写回 DTO（如果需要）
        pondDTO.setId(pond.getId());

        // 插入价格段
        if (pondDTO.getPriceSegments() != null && !pondDTO.getPriceSegments().isEmpty()) {
            for (PriceSegment priceSegment : pondDTO.getPriceSegments()) {
                priceSegment.setPondId(pond.getId());
            }
            pondMapper.insertPriceSegment(pondDTO.getPriceSegments());
        }

        return rows;
    }


    @Override
    public int updatePond(PondDTO pondDTO) {
        pondDTO.setUpdateTime(DateUtils.getNowDate());

        // ✅ DTO 转 Entity，处理 fishTypes 转换
        Pond pond = new Pond();
        pond.setId(pondDTO.getId());
        pond.setName(pondDTO.getName());
        pond.setDeptId(pondDTO.getDeptId());
        pond.setBackgroundUrl(pondDTO.getBackgroundUrl());
        pond.setIsReturnFish(pondDTO.getIsReturnFish());
        pond.setCurrentWeight(pondDTO.getCurrentWeight());
        pond.setUpdateTime(pondDTO.getUpdateTime());
        pond.setRemark(pondDTO.getRemark());

        // fishTypes List<String> → String
        if (pondDTO.getFishTypes() != null && !pondDTO.getFishTypes().isEmpty()) {
            pond.setFishTypes(String.join(",", pondDTO.getFishTypes()));
        } else {
            pond.setFishTypes(null);
        }

        int rows = pondMapper.updatePond(pond);

        // ✅ 处理价格段
        pondMapper.deletePriceSegmentsByPondId(pond.getId());
        if (pondDTO.getPriceSegments() != null && !pondDTO.getPriceSegments().isEmpty()) {
            for (PriceSegment priceSegment : pondDTO.getPriceSegments()) {
                priceSegment.setPondId(pond.getId());
            }
            pondMapper.insertPriceSegment(pondDTO.getPriceSegments());
        }

        return rows;
    }


    @Override
    public int deletePondByIds(Long[] ids)
    {
        if (ids == null || ids.length == 0) {
            throw new IllegalArgumentException("删除操作必须提供有效的鱼塘ID");
        }
        for (Long id : ids) {
            pondMapper.deletePriceSegmentsByPondId(id);
        }
        return pondMapper.deletePondByIds(ids);
    }

    @Override
    public int updatePondBackground(Long pondId, String backgroundUrl) {
        return pondMapper.updatePondBackground(pondId, backgroundUrl);
    }


    @Override
    @Transactional
    public int addCommentPond(PondComment pondComment) {
        int result = pondCommentMapper.insert(pondComment);
        Long commentId = pondComment.getId();

        List<PondCommentImage> pondCommentImages = pondComment.getImages();

        if (pondCommentImages != null && !pondCommentImages.isEmpty()) {
            for (PondCommentImage pondCommentImage : pondCommentImages) {
                pondCommentImage.setCommentId(commentId);
                pondCommentImageMapper.insert(pondCommentImage);
            }
        }
        return result;
    }

    @Override
    public List<PondCommentVo> getCommentPond() {
        List<PondComment> pondComments = pondCommentMapper.selectList(
                new QueryWrapper<PondComment>().orderByDesc("create_time")
        );

        if (pondComments.isEmpty()) {
            return Collections.emptyList();
        }

        Set<Long> userIds = pondComments.stream()
                .map(PondComment::getUserId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Set<Long> deptIds = pondComments.stream()
                .map(PondComment::getDeptId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        Set<Long> pondIds = pondComments.stream()
                .map(PondComment::getPondId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 调用远程服务获取用户和部门信息
        List<SysUser> userList = Optional.ofNullable(sysUserClient.getUserBatch(new ArrayList<>(userIds)).getData())
                .orElse(Collections.emptyList());
        Map<Long, String> userNameMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getUserId, SysUser::getNickName));

        List<SysDept> deptList = Optional.ofNullable(deptClient.getDeptBatch(new ArrayList<>(deptIds)).getData())
                .orElse(Collections.emptyList());
        Map<Long, String> deptNameMap = deptList.stream()
                .collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName));

        List<Pond> pondList = pondMapper.selectBatchIds(new ArrayList<>(pondIds));
        Map<Long, String> pondNameMap = pondList.stream()
                .collect(Collectors.toMap(Pond::getId, Pond::getName));

        List<PondCommentVo> result = new ArrayList<>();

        log.info("评论总数: {}", pondComments.size());
        log.info("userIds: {}", userIds);
        log.info("deptIds: {}", deptIds);
        log.info("pondIds: {}", pondIds);

        log.info("userList size: {}, content: {}", userList.size(), userList);
        log.info("deptList size: {}, content: {}", deptList.size(), deptList);
        log.info("pondList size: {}, content: {}", pondList.size(), pondList);
        for (PondComment pondComment : pondComments) {
            PondCommentVo vo = new PondCommentVo();
            BeanUtils.copyProperties(pondComment, vo);

            vo.setPondName(pondNameMap.getOrDefault(pondComment.getPondId(), "未知塘口"));
            vo.setUserName(userNameMap.getOrDefault(pondComment.getUserId(), "匿名用户"));
            vo.setDeptName(deptNameMap.getOrDefault(pondComment.getDeptId(), "未知钓场"));

            List<PondCommentImage> images = pondCommentImageMapper.selectList(
                    new QueryWrapper<PondCommentImage>().eq("comment_id", pondComment.getId())
            );
            vo.setImageList(images);

            result.add(vo);
        }

        return result;
    }


    @Override
    public List<PondCommentVo> getCommentPondByDeptId(Long deptId){
        QueryWrapper<PondComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id",deptId).orderByDesc("create_time");

        List<PondComment> pondComments = pondCommentMapper.selectList(queryWrapper);

        List<PondCommentVo> result = new ArrayList<>();
        for (PondComment pondComment : pondComments) {
            PondCommentVo pondCommentVo = new PondCommentVo();
            BeanUtils.copyProperties(pondComment,pondCommentVo);

            List<PondCommentImage> imageUrls = pondCommentImageMapper.selectList(
                    new QueryWrapper<PondCommentImage>().eq("comment_id",pondComment.getId())
            );
            pondCommentVo.setImageList(imageUrls);
            result.add(pondCommentVo);
        }
        return result;
    }


    @Override
    public int deleteCommentPondByIds(Long[] ids){
       return pondCommentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public int updateCommentPond(PondCommentVo pondCommentVo){
        PondComment pondComment = new PondComment();
        BeanUtils.copyProperties(pondCommentVo, pondComment);

        Long commentId = pondComment.getId();
        // 1. 删除旧图片
        pondCommentImageMapper.delete(
                new QueryWrapper<PondCommentImage>().eq("comment_id", commentId)
        );

        // 2. 插入新图片
        List<PondCommentImage> newImages = pondCommentVo.getImageList();
        if (newImages != null && !newImages.isEmpty()) {
            for (PondCommentImage image : newImages) {
                image.setCommentId(commentId);
                pondCommentImageMapper.insert(image);
            }
        }
        return pondCommentMapper.updateById(pondComment);
    }

    @Override
    public int addFacility(PondFacilityDTO pondFacilityDTO){
        deptFacilityRelationMapper.deleteByDeptId(pondFacilityDTO.getDeptId());
        return deptFacilityRelationMapper.batchInsert(pondFacilityDTO);
    }

    @Override
    public List<DeptFacilityRelation> getFacility(Long deptId) {
        return deptFacilityRelationMapper.selectList(
                new QueryWrapper<DeptFacilityRelation>().eq("dept_id", deptId)
        );
    }

}
